//
//  IntegralViewController.m
//  PHMall
//
//  Created by admin on 2018/1/21.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "IntegralViewController.h"
#import "Orderheader.h"
#import "DetailCell.h"
#import "FinancialModel.h"
#define But_Tag 1000;

@interface IntegralViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    Orderheader *_headView;
    UIScrollView *_scrollView;
    NSInteger type;
    NSInteger start;
}
@property(nonatomic,strong)MBProgressHUD *hud;
@property(strong,nonatomic)UITableView *myTableview;
@property(nonatomic,strong)NSMutableArray *funddetails;
@end

@implementation IntegralViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navBarBgAlpha=@"1.0";
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        self.myTableview.estimatedRowHeight = 0;
        self.myTableview.estimatedSectionFooterHeight = 0;
        self.myTableview.estimatedSectionHeaderHeight = 0;
        self.myTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    type=start=0;
    [self refreshFunddetails:YES];
    [self setUI];
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    self.myTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    self.myTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
    self.myTableview.mj_footer.hidden=YES;
    // Do any additional setup after loading the view.
}
-(void)HeaderRefresh{
    start=0;
    [self refreshFunddetails:NO];
}
-(void)footeRefresh{
    start=self.funddetails.count;
    [self refreshFunddetails:YES];
}
-(void)setUI{
    
    __weak typeof(self) weakSelf = self;
    _headView = [[Orderheader alloc]init];
    _headView.backgroundColor=[UIColor colorWithHexString:@"#E7EBEE"];
    [self.view addSubview:_headView];
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.height.offset(40);
    }];
    _headView.backgroundColor=[UIColor colorWithHexString:@"#f8fafd"];
    _headView.itemClickAtIndex = ^(NSInteger index){
        [weakSelf adjustScrollView:index];
    };
    _headView.items = @[Localized(@"全部"),Localized(@"收入"),Localized(@"支出")];
    
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headView.mas_bottom).priorityHigh();
        make.left.right.equalTo(self.view).priorityHigh();
        make.bottom.equalTo(self.view).with.offset(-self.tabBar_height).priorityHigh();
    }];
}
#pragma mark-通过点击button来改变scrollview的偏移量
-(void)adjustScrollView:(NSInteger)index
{
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
    switch (index) {
        case 0:
            type=start=0;
            [self refreshFunddetails:YES];
            break;
        case 1:
            type=1;
            start=0;
            [self refreshFunddetails:YES];
            break;
        case 2:
            type=-1;
            start=0;
            [self refreshFunddetails:YES];
            break;
        default:
            break;
    }
}
- (void)refreshFunddetails:(BOOL)reload{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"pointdetails"];
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)type] forKey:@"type"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)start] forKey:@"start"];
    [httpTool ZBPostNetDataWith:urlstr withDic:dict andSuccess:^(id responseObject) {
        if (start==0) {
            self.emptyType=EmptyDataSetNoData;
            [self.funddetails removeAllObjects];
            if (reload) {
                 [self.myTableview setContentOffset:CGPointMake(0, 0) animated:NO];
            }
        }
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[NSString stringWithFormat:@"%@",responseDict[@"ret"]] isEqualToString:@"200"]) {
            NSMutableArray *data=responseDict[@"data"];
            if (data.count==0) {
                [self.myTableview.mj_header endRefreshing];
                [self.myTableview.mj_footer endRefreshingWithNoMoreData];
                if (reload) {
                    [self.myTableview reloadData];
                }
            }else{
                [self analysisDataWithFunddetailsDictionary:data];
            }
        }
        
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
        self.myTableview.mj_footer.hidden=YES;
        [self.funddetails removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        
        [self.myTableview reloadData];
        [self.myTableview.mj_header endRefreshing];
        [self.myTableview.mj_footer endRefreshing];
    }];
}
- (void)analysisDataWithFunddetailsDictionary:(NSMutableArray *)array{
    for (NSMutableDictionary *dict in array) {
        FinancialModel *model = [FinancialModel yy_modelWithDictionary:dict];
        [self.funddetails addObject:model];
    }
    
    if (self.funddetails.count!=0) {
        //数量少于2条时隐藏上拉加载
        if (self.funddetails.count<10) {
            self.myTableview.mj_footer.hidden=YES;
        }else{
            self.myTableview.mj_footer.hidden=NO;
        }
    }else{
        //数量为0条时隐藏上拉加载
        self.myTableview.mj_footer.hidden=YES;
    }
    
    
    [self.myTableview reloadData];
    [self.myTableview.mj_header endRefreshing];
    [self.myTableview.mj_footer endRefreshing];
    
    
}

#pragma mark - tableView
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.funddetails.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCell *cell=[DetailCell theShareCellWithTableView:tableView];
    FinancialModel *model=self.funddetails[indexPath.row];
    cell.model=model;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    EvaluateVC *evaluate=[[EvaluateVC alloc]init];
    //    [self.navigationController pushViewController:evaluate animated:YES];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            return [UIImage imageNamed:@"订单缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
    
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:@"你还没有相关的订单！\n可以去看看有哪些想买的。"];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:20],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, 10)];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange(10, 12)];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    start=0;
    [self refreshFunddetails:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}

//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource=self;
        _myTableview.emptyDataSetDelegate=self;
    }
    return _myTableview;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSMutableArray *)funddetails{
    if (!_funddetails) {
        _funddetails=[[NSMutableArray alloc] init];
    }
    return _funddetails;
}
@end
